<form id="TaskForm"  action="{:sysuri()}" method="post" data-auto="true" class="layui-form layui-card" data-table-id="TaskTable">
    <div class="layui-card-body">
<!--        <div class="layui-form-item">-->
<!--            <label class="layui-form-label label-required-next">发单人</label>-->
<!--            <div class="layui-input-block">-->
<!--                <select name='merchant_id' required class='layui-select' lay-search>-->
<!--                    <option value=''>请选择发单人</option>-->
<!--                    {foreach $merchant_list as $merchant}{eq name='$merchant.id' value='$vo.merchant_id|default=0'}-->
<!--                    <option selected value='{$merchant.id}'>{$merchant.company|default=" - "} [{$merchant.nickname|default=" - "}]</option>-->
<!--                    {else}-->
<!--                    <option value='{$merchant.id}'>{$merchant.company|default=" - "} [{$merchant.nickname|default=" - "}]</option>-->
<!--                    {/eq}{/foreach}-->
<!--                </select>-->
<!--                <p class="help-block"></p>-->
<!--            </div>-->
<!--        </div>-->

        <div class="layui-form-item"  style="display: none">
            <label class="layui-form-label label-required-next">订单任务分类</label>
            <div class="layui-input-block">
                <select name='category_id' required class='layui-select' lay-search lay-filter="category_id">
                    <option value=''>请选择订单任务分类</option>
                    {foreach $category_list as $category}{eq name='$category.id' value='$vo.category_id|default=0'}
                    <option selected value='{$category.id}'>{$category.name}</option>
                    {else}
                    <option value='{$category.id}'>{$category.name}</option>
                    {/eq}{/foreach}
                </select>
                <p class="help-block"></p>
            </div>
        </div>

        <!--        <div class="layui-form-item">-->
        <!--            <label class="layui-form-label">订单任务名称</label>-->
        <!--            <div class="layui-input-block">-->
        <!--                <input name="name" value='{$vo.name|default=""}' required placeholder="请输入订单任务名称" class="layui-input">-->
        <!--                <p class="help-block"></p>-->
        <!--            </div>-->
        <!--        </div>-->


        <div class="layui-form-item transport-cate">
            <label class="layui-form-label label-required-next">货物种类</label>
            <div class="layui-input-block">
                <select name='transport_type' required class='layui-select' lay-search lay-filter="transport_type">
                    <option value=''>请选择货物种类</option>
                    {foreach :explode('；', sysconf('transport_type_list')) as $type}{eq name='$type' value='$vo.transport_type|default=""'}
                    <option selected value='{$type}'>{$type}</option>
                    {else}
                    <option value='{$type}'>{$type}</option>
                    {/eq}{/foreach}
                </select>
                <input name="transport_type_other" value='{$vo.transport_type_other|default=""}' required placeholder="请输入其他种类" class="layui-input layui-hide">
                <p class="help-block"></p>
            </div>
        </div>



        <div class="layui-form-item transport-cate">
            <label class="layui-form-label label-required-next">运输场景</label>
            <div class="layui-input-block">
                <select name='transport_scene' required class='layui-select' lay-search lay-filter="transport_scene">
                    <option value=''>请选择运输场景</option>
                    {foreach :explode('；', sysconf('transport_scene_list')) as $scene}{eq name='$scene' value='$vo.transport_scene|default=""'}
                    <option selected value='{$scene}'>{$scene}</option>
                    {else}
                    <option value='{$scene}'>{$scene}</option>
                    {/eq}{/foreach}
                </select>
                <input  name="transport_scene_other" value='{$vo.transport_scene_other|default=""}' required placeholder="请输入其他场景" class="layui-input layui-hide">
                <p class="help-block"></p>
            </div>
        </div>

        <div class="layui-form-item transport-cate">
            <label class="layui-form-label label-required-next">订单距离</label>
            <div class="layui-input-block">
                <select name='transport_distance' required class='layui-select' lay-search >
                    <option value=''>请选择订单距离</option>
                    {foreach :explode('；', sysconf('transport_distance_list')) as $distance}{eq name='$distance' value='$vo.transport_distance|default=""'}
                    <option selected value='{$distance}'>{$distance}</option>
                    {else}
                    <option value='{$distance}'>{$distance}</option>
                    {/eq}{/foreach}
                </select>
                <p class="help-block"></p>
            </div>
        </div>

        <div class="layui-form-item transport-cate">
            <label class="layui-form-label">货物重量</label>
            <div class="layui-input-block">
                <input name="weight" value='{$vo.weight|default=""}' required placeholder="请输入货物重量" class="layui-input">
                <p class="help-block">单位：吨</p>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">任务时间</label>
            <div class="layui-input-block">
                <input id="exectime" name="exec_at" value='{$vo.exec_at|default=""}' required placeholder="请选择订单任务时间" class="layui-input">
                <p class="help-block"></p>
            </div>
        </div>

        <!--        <div class="layui-form-item transport-cate">-->
        <!--            <label class="layui-form-label">开始时间</label>-->
        <!--            <div class="layui-input-block">-->
        <!--                <input id="starttime" name="start_at" value='{$vo.start_at|default=""}' required placeholder="请选择开始时间" class="layui-input">-->
        <!--                <p class="help-block"></p>-->
        <!--            </div>-->
        <!--        </div>-->

        <!--        <div class="layui-form-item transport-cate">-->
        <!--            <label class="layui-form-label">结束时间</label>-->
        <!--            <div class="layui-input-block">-->
        <!--                <input id="endtime" name="end_at" value='{$vo.end_at|default=""}' required placeholder="请选择结束时间" class="layui-input">-->
        <!--                <p class="help-block"></p>-->
        <!--            </div>-->
        <!--        </div>-->

        <div class="layui-form-item">
            <label class="layui-form-label label-required ">省市区</label>
            <div class="layui-input-block">
                <div style="display: inline-block;">
                    <div class="layui-input-inline">
                        <select name="province" id="province" lay-filter="province" lay-verify="required">
                            <option value="">请选择省份</option>
                        </select>
                    </div>
                    <div class="layui-input-inline">
                        <select name="city" id="city" lay-filter="city" lay-verify="required">
                            <option value="">请选择城市</option>
                        </select>
                    </div>
                    <div class="layui-input-inline">
                        <select name="area" id="area" lay-filter="area" lay-verify="required">
                            <option value="">请选择区县</option>
                        </select>
                    </div>
                </div>
                <p class="help-block" style="margin-top: -8px">可通过下方地图自动获取</p>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label ">详细地址</label>
            <div class="layui-input-block">
                <input  name="address" value='{$vo.address|default=""}' required placeholder="请输入订单任务详细地址" class="layui-input">
                <p class="help-block">可通过下方地图自动获取</p>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">地址经纬度</label>
            <div class="layui-input-block">
                <input  name="latlng" value='{$vo.latlng|default=""}' required placeholder="请输入地址经纬度" class="layui-input">
                <p class="help-block">可通过下方地图自动获取，英文逗号分隔经纬度</p>
                <!--                <div style="height: 600px; border: 1px solid #ddd">-->
                <!--                    <iframe id="mapPage" width="100%" height="100%" frameborder=0 src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key={:sysconf('tencent_map_key')}&referer=feitu&&coord={$vo.latlng|default=''}"></iframe>-->
                <!--                </div>-->
                <div id="choose-position" class="layui-btn layui-btn-sm layui-btn-primary">点击选择详细地址</div>
                <p class="help-block"></p>
            </div>
        </div>


        <!--        <div class="layui-form-item transport-cate">-->
        <!--            <label class="layui-form-label label-required">送达省市区</label>-->
        <!--            <div class="layui-input-block">-->
        <!--                <div style="display: inline-block;">-->
        <!--                    <div class="layui-input-inline">-->
        <!--                        <select name="province2" id="province2" lay-filter="province2" lay-verify="required">-->
        <!--                            <option value="">请选择省份</option>-->
        <!--                        </select>-->
        <!--                    </div>-->
        <!--                    <div class="layui-input-inline">-->
        <!--                        <select name="city2" id="city2" lay-filter="city2" lay-verify="required">-->
        <!--                            <option value="">请选择城市</option>-->
        <!--                        </select>-->
        <!--                    </div>-->
        <!--                    <div class="layui-input-inline">-->
        <!--                        <select name="area2" id="area2" lay-filter="area2" lay-verify="required">-->
        <!--                            <option value="">请选择区县</option>-->
        <!--                        </select>-->
        <!--                    </div>-->
        <!--                </div>-->
        <!--                <p class="help-block" style="margin-top: -8px">可通过下方地图自动获取</p>-->
        <!--            </div>-->
        <!--        </div>-->

        <!--        <div class="layui-form-item transport-cate">-->
        <!--            <label class="layui-form-label">送达详细地址</label>-->
        <!--            <div class="layui-input-block">-->
        <!--                <input  name="address2" value='{$vo.address2|default=""}' required placeholder="请输入订单任务详细地址" class="layui-input">-->
        <!--                <p class="help-block">可通过下方地图自动获取</p>-->
        <!--            </div>-->
        <!--        </div>-->

        <!--        <div class="layui-form-item transport-cate">-->
        <!--            <label class="layui-form-label">送达地址经纬度</label>-->
        <!--            <div class="layui-input-block">-->
        <!--                <input  name="latlng2" value='{$vo.latlng2|default=""}' required placeholder="请输入地址经纬度" class="layui-input">-->
        <!--                <p class="help-block">可通过下方地图自动获取，英文逗号分隔经纬度</p>-->
        <!--&lt;!&ndash;                <div style="height: 600px; border: 1px solid #ddd">&ndash;&gt;-->
        <!--&lt;!&ndash;                    <iframe id="mapPage2" width="100%" height="100%" frameborder=0 src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key={:sysconf('tencent_map_key')}&referer=feitu&&coord={$vo.latlng|default=''}"></iframe>&ndash;&gt;-->
        <!--&lt;!&ndash;                </div>&ndash;&gt;-->
        <!--                <div id="choose-position-2" class="layui-btn layui-btn-sm layui-btn-primary">点击选择详细地址</div>-->
        <!--                <p class="help-block"></p>-->
        <!--            </div>-->
        <!--        </div>-->


        <div class="layui-form-item">
            <label class="layui-form-label">预估价格</label>
            <div class="layui-input-block">
<!--                <input name="money" value='{$vo.money|default=""}' required placeholder="请输入订单任务报酬" class="layui-input">-->
                <div style="display: flex;">
                    <input name="money" value='{$vo.money|default=""}'  placeholder="请输入订单任务报酬" class="layui-input">
                    <div class="layui-btn calc-price">计算价格</div>
                </div>
                <p class="help-block">单位：元</p>
            </div>
        </div>

        <!--        <div class="layui-form-item">-->
        <!--            <label class="layui-form-label">订单任务描述</label>-->
        <!--            <div class="layui-input-block">-->
        <!--                <textarea name="desc" required placeholder="请输入订单任务描述" class="layui-textarea">{$vo.desc|default=""}</textarea>-->
        <!--                <p class="help-block"></p>-->
        <!--            </div>-->
        <!--        </div>-->

        <div class="layui-form-item">
            <label class="layui-form-label">订单要求</label>
            <div class="layui-input-block">
                <textarea name="require" required placeholder="请输入订单任务要求" class="layui-textarea">{$vo.require|default=""}</textarea>
                <p class="help-block"></p>
            </div>
        </div>

<!--        <div class="layui-form-item">-->
<!--            <label class="layui-form-label label-required">审核文件</label>-->
<!--            <div class="layui-input-block">-->
<!--                <div class="relative block label-required-null">-->
<!--                    <input class="layui-input" required  placeholder="请上传审核文件" value="{$vo.file|default=''}" name="file">-->
<!--                    <a class="input-right-icon layui-icon layui-icon-upload-drag" data-file="btn" data-field="file"></a>-->
<!--                </div>-->
<!--                <p class="help-block"></p>-->
<!--            </div>-->
<!--        </div>-->
    </div>

    <div class="hr-line-dashed"></div>
    {notempty name='vo.id'}<input type='hidden' value='{$vo.id}' name='id'>{/notempty}

    <div class="layui-form-item text-center">
        <button class="layui-btn" type='submit'>保存数据</button>
        <button class="layui-btn layui-btn-danger" type='button' data-confirm="确定要取消编辑吗？" data-close>取消编辑</button>
    </div>
</form>

<script>
    $(function () {
        // 时间选择器
        laydate.render({elem: '#exectime', type: 'datetime'});
        // laydate.render({elem: '#starttime', type: 'datetime'});
        // laydate.render({elem: '#endtime', type: 'datetime'});

        // 计算预估价格
        $('.calc-price').click(function (){
            let transport_distance_list_obj = JSON.parse( '{:json_encode($transport_distance_list_obj)}');
            let transport_distance = $('[name="transport_distance"]').val();
            let distance = transport_distance_list_obj[transport_distance] ? Number(transport_distance_list_obj[transport_distance].distance) : 0;
            let money = 0;
            let weight = $('[name="weight"]').val();
            if(distance < 300){
                money = 150 * Number(weight);
            }else{
                let per = 200 * (1 + (distance - 300) / 300 * 0.8);
                per = parseFloat(per.toFixed(2));
                money = per * Number(weight);
            }
            money = money > 999 ? money : 999;
            money = money.toFixed(2);
            $('[name="money"]').val(money);
        })

        // 省市区数据
        var area_data = JSON.parse('{:json_encode($area_list)}');
        // 省份选择
        function changeProvince(provinceName) {
            $('#province').val(provinceName);
            $('#city').empty().append('<option value="">请选择城市</option>');
            $('#area').empty().append('<option value="">请选择区县</option>');
            var provinceData = findChildren(provinceName, 1);
            if (provinceData && provinceData.children) {
                $.each(provinceData.children, function(index, city){
                    $('#city').append(new Option(city.name, city.name));
                });
            }
            form.render('select');
        }
        // 城市选择
        function changeCity(cityName) {
            $('#city').val(cityName);
            $('#area').empty().append('<option value="">请选择区县</option>');
            var cityData = findChildren(cityName, 2);
            if (cityData && cityData.children) {
                $.each(cityData.children, function(index, area){
                    $('#area').append(new Option(area.name, area.name));
                });
            }
            form.render('select');
        }
        // 区县选择
        function changeArea(areaName) {
            $('#area').val(areaName);
            form.render('select');
        }
        // 查找子节点函数
        function findChildren(name, level=1){
            for(var i = 0; i < area_data.length; i++){
                if(area_data[i].name == name && level==1){
                    return area_data[i];
                } else if(area_data[i].children){
                    for(var j = 0; j < area_data[i].children.length; j++){
                        if(area_data[i].children[j].name == name && level==2){
                            return area_data[i].children[j];
                        }
                    }
                }
            }
            return null;
        }

        // 字符串去除前缀
        function removePrefix(str, pre) {
            if (str.startsWith(pre)) {
                return str.substring(pre.length);
            }
            return str;
        }



        // 省份选择
        // function changeProvince2(provinceName) {
        //     $('#province2').val(provinceName);
        //     $('#city2').empty().append('<option value="">请选择城市</option>');
        //     $('#area2').empty().append('<option value="">请选择区县</option>');
        //     var provinceData = findChildren(provinceName, 1);
        //     if (provinceData && provinceData.children) {
        //         $.each(provinceData.children, function(index, city){
        //             $('#city2').append(new Option(city.name, city.name));
        //         });
        //     }
        //     form.render('select');
        // }
        // // 城市选择
        // function changeCity2(cityName) {
        //     $('#city2').val(cityName);
        //     $('#area2').empty().append('<option value="">请选择区县</option>');
        //     var cityData = findChildren(cityName, 2);
        //     if (cityData && cityData.children) {
        //         $.each(cityData.children, function(index, area){
        //             $('#area2').append(new Option(area.name, area.name));
        //         });
        //     }
        //     form.render('select');
        // }
        // // 区县选择
        // function changeArea2(areaName) {
        //     $('#area2').val(areaName);
        //     form.render('select');
        // }

        function toggleTransportCate(categoryId) {
            const isTransport = categoryId == 1;
            $(".transport-cate").toggle(isTransport);
            $(".no-transport-cate").toggle(!isTransport);
        }

        function showTransportTypeOther(type){
            if (type == '其他'){
                $('[name=transport_type_other]').show();
            }else{
                $('[name=transport_type_other]').hide();
            }
        }

        function showTransportSceneOther(scene){
            if (scene == '其他'){
                $('[name=transport_scene_other]').show();
            }else{
                $('[name=transport_scene_other]').hide();
            }
        }

        layui.use(['form','jquery'], function(){
            var form = layui.form;
            var $ = layui.jquery

            // 初始值
            var initialProvince = '{$vo.province|default=""}';
            var initialCity = '{$vo.city|default=""}';
            var initialArea = '{$vo.area|default=""}';

            // 省份选择事件
            form.on('select(province)', function(data){
                var selectedProvinceName = data.value;
                changeProvince(selectedProvinceName);
            });

            // 城市选择事件
            form.on('select(city)', function(data){
                var selectedCityName = data.value;
                changeCity(selectedCityName);
            });

            // 初始化省份
            $.each(area_data, function(index, item){
                $('#province').append(new Option(item.name, item.name));
            });
            changeProvince(initialProvince);
            changeCity(initialCity);
            changeArea(initialArea);


            // // 初始值
            // var initialProvince2 = '{$vo.province2|default=""}';
            // var initialCity2 = '{$vo.city2|default=""}';
            // var initialArea2 = '{$vo.area2|default=""}';
            //
            // // 省份选择事件
            // form.on('select(province2)', function(data){
            //     var selectedProvinceName = data.value;
            //     changeProvince2(selectedProvinceName);
            // });
            //
            // // 城市选择事件
            // form.on('select(city2)', function(data){
            //     var selectedCityName = data.value;
            //     changeCity2(selectedCityName);
            // });
            //
            // // 初始化省份
            // $.each(area_data, function(index, item){
            //     $('#province2').append(new Option(item.name, item.name));
            // });
            // changeProvince2(initialProvince2);
            // changeCity2(initialCity2);
            // changeArea2(initialArea2);


            // 监听分类修改
            form.on('select(category_id)', function(data){
                toggleTransportCate(data.value);
            });

            // 监听货物种类修改
            form.on('select(transport_type)', function(data){
                showTransportTypeOther(data.value);
            });

            // 监听运输场景修改
            form.on('select(transport_scene)', function(data){
                showTransportSceneOther(data.value);
            });

            // 初始化时执行一次
            toggleTransportCate($('#TaskForm [name=category_id]').val());
            showTransportTypeOther($('#TaskForm [name=transport_type]').val())
            showTransportSceneOther($('#TaskForm [name=transport_scene]').val())
        });


        var layer_ids = '';
        var map_id = '';
        $('#choose-position').click(function (){
            map_id = 1;
            layer_ids = $.form.iframe("https://apis.map.qq.com/tools/locpicker?search=1&type=1&key={:sysconf('tencent_map_key')}&referer=feitu&&coord={$vo.latlng|default=''}",
                '选择详细地址', ['800px', '70vh'])
        })
        $('#choose-position-2').click(function (){
            map_id = 2;
            layer_ids = $.form.iframe("https://apis.map.qq.com/tools/locpicker?search=1&type=1&key={:sysconf('tencent_map_key')}&referer=feitu&&coord={$vo.latlng2|default=''}",
                '选择详细地址', ['800px', '70vh'])
        })
        window.addEventListener('message', function(event) {
            $.msg.close(layer_ids)
            console.log(map_id);
            if (map_id == 1) {
                var loc = event.data;
                console.log('location', loc);
                $("[name=latlng]").val(loc.latlng.lat + ',' + loc.latlng.lng);
                // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
                if (loc && loc.module == 'locationPicker') {
                    $.ajax({
                        url: "https://apis.map.qq.com/ws/geocoder/v1?key={:sysconf('tencent_map_key')}&output=jsonp&location=" + loc.latlng.lat + ',' + loc.latlng.lng,
                        dataType: 'jsonp',
                        type: 'GET',
                        contentType: 'application/json',
                        success: function (data) {
                            console.log(data);
                            var add = data.result.address_component;
                            var province = add.province;
                            var city = add.city;
                            var area = add.district;
                            changeProvince(province);
                            changeCity(city);
                            changeArea(area);
                            $("[name=address]").val(removePrefix(loc.poiaddress + loc.poiname, province + city + area));
                        },
                        error: function (xhr, status, error) {
                            console.error('Error:', error);
                        }
                    });
                }
            }else{
                var loc = event.data;
                console.log('location', loc);
                $("[name=latlng2]").val(loc.latlng.lat + ',' + loc.latlng.lng);
                // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
                if (loc && loc.module == 'locationPicker') {
                    $.ajax({
                        url: "https://apis.map.qq.com/ws/geocoder/v1?key={:sysconf('tencent_map_key')}&output=jsonp&location=" + loc.latlng.lat + ',' + loc.latlng.lng,
                        dataType: 'jsonp',
                        type: 'GET',
                        contentType: 'application/json',
                        success: function (data) {
                            console.log(data);
                            var add = data.result.address_component;
                            var province = add.province;
                            var city = add.city;
                            var area = add.district;
                            changeProvince2(province);
                            changeCity2(city);
                            changeArea2(area);
                            $("[name=address2]").val(removePrefix(loc.poiaddress + loc.poiname, province + city + area));
                        },
                        error: function (xhr, status, error) {
                            console.error('Error:', error);
                        }
                    });
                }
            }
        }, false);
    });
</script>